<!DOCTYPE html>
<html>
<head>
  <title>小球下落动画</title>
  <style>
    canvas {
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <canvas id="myCanvas" width="800" height="600"></canvas>
  <script>
    const canvas = document.getElementById("myCanvas");
    const ctx = canvas.getContext("2d");

    class Ball {
      constructor(x, y, radius, color) {
        this.x = x;
        this.y = y;
        this.radius = radius;
        this.color = color;
        this.velocity = { x: 0, y: 0 };
        this.friction = 0.95; // 摩擦力
        this.isDropping = false; // 是否正在下落
        this.dropInterval = 2000; // 下落间隔时间（毫秒）
        this.nextDropTime = Date.now() + this.dropInterval; // 下一次下落时间
      }

      draw() {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
        ctx.fillStyle = this.color;
        ctx.fill();
        ctx.closePath();
      }

      update() {
        this.velocity.y += 0.5; // 重力加速度
        this.x += this.velocity.x;
        this.y += this.velocity.y;

        // 检测小球是否与平面发生碰撞
        if (this.y + this.radius > canvas.height) {
          this.y = canvas.height - this.radius; // 修正小球位置
          this.velocity.y = -this.velocity.y * this.friction; // 反弹并减速
          this.velocity.x *= this.friction; // 同时减速水平方向
        }

        // 如果小球停止运动，设置下一次下落时间
        if (this.velocity.x === 0 && this.velocity.y === 0 && !this.isDropping) {
          this.isDropping = true;
          this.nextDropTime = Date.now() + this.dropInterval;
        }

        // 如果到了下一次下落时间，重置小球位置和速度
        if (this.isDropping && Date.now() >= this.nextDropTime) {
          this.x = Math.random() * (canvas.width - this.radius * 2) + this.radius;
          this.y = -this.radius;
          this.velocity.y = 0;
          this.isDropping = false;
        }
      }
    }

    const ball = new Ball(50, 50, 10, "red");

    function animate() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ball.update();
      ball.draw();
      requestAnimationFrame(animate);
    }

    animate();
  </script>
</body>
</html>